package com.hama.iotrust.common.mybatis.criteria;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hama.iotrust.common.mybatis.criteria.Criteria;
import com.hama.iotrust.common.mybatis.criteria.CriteriaException;
import com.hama.iotrust.common.mybatis.criteria.Expression;

/**
 * IN (A, B, C) 表达式
 * 
 * @param <T>
 * @author 金建强(ptma@163.com)
 * @version 1.0.0
 * @since 2012-3-15 下午05:53:12
 */
public class InExpression implements Expression {

    private String       m_propName;
    private String       m_columnName = null;
    private List<Object> m_values;
    Map<String, Object>  params       = new HashMap<String, Object>();

    private Criteria<?>  m_crit;

    InExpression(String propertyName, Object[] values){
        m_propName = propertyName;
        m_values = Arrays.asList(values);
    }

    public String getSql() {
        params.clear();
        StringBuilder sb = new StringBuilder();
        sb.append("(");
        if (m_columnName == null) {
            sb.append("< not bound:").append(m_propName).append(">");
        } else {
            sb.append(m_columnName);
        }
        sb.append(" IN (");
        for (int i = 0; i < m_values.size(); i++) {
            String tmpParam = m_propName + m_crit.nextParamSuffix();
            params.put(tmpParam, m_values.get(i));
            sb.append("#{" + Criteria.PARAM_PREFIX + tmpParam + "}");
            if (i < m_values.size() - 1) sb.append(",");
        }
        sb.append("))");
        return sb.toString();
    }

    public Map<String, Object> getParameter() {
        return params;
    }

    public boolean verify(Criteria<?> criteria) {
        return criteria.hasProperty(m_propName);
    }

    public void bind(Criteria<?> crit) throws CriteriaException {
        m_crit = crit;
        m_columnName = crit.toColumnName(m_propName);
    }
}
